package com.lcb.manager.interceptor;

import com.lcb.manager.configuration.Config;
import com.lcb.manager.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: cxy
 * @Date: 2019/1/10
 * @Description: 拦截器
 */
public class GlobalDataInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(GlobalDataInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        Boolean is_login = (Boolean) request.getSession().getAttribute("is_login");
        logger.info(request.getRequestURI());
        if (is_login == null || !is_login) {
            response.sendRedirect("/");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        if (modelAndView != null) {
            ModelMap modelMap = modelAndView.getModelMap();
            if (modelMap != null) {
                User user= (User) request.getSession().getAttribute("user");
                modelMap.put("user", user);
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
